package com.pig4cloud.pig.ads.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.api.client.util.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * http 请求工具类
 * @author frank
 * @version 1.0 , 2016-5-29
 * @since JDK1.8
 */
public class HttpUtils {

	public static String CONTENT_CHARSET_UTF8 = "UTF-8";

	public static String CONTENT_TYPE_JSON_UTF8 = "application/json; charset="+ CONTENT_CHARSET_UTF8;
	private final static String authPrix="Bearer ";

	private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

	/**
	 * 默认连接超时毫秒数
	 * 单位：milliseconds
	 */
	public static int DEFAULT_CONNECT_TIMEOUT = 10000;

	/**
	 * 默认socket超时毫秒数
	 * 单位：milliseconds
	 */
	public static int DEFAULT_SOCKET_TIMEOUT = 10000;

	/**
	 * 简单地址访问，使用GET方法请求，返回内容体
	 * @param url
	 */
	public static String doGet(String url,Map<String,String> headers,String charset){
		CloseableHttpClient client = null;
		try {
			client = HttpClients.createDefault();
			HttpGet get = new HttpGet(url);
			RequestConfig requestConfig = RequestConfig.custom()
					.setSocketTimeout(DEFAULT_CONNECT_TIMEOUT)
					.setConnectTimeout(DEFAULT_SOCKET_TIMEOUT)
					.build();
			get.setConfig(requestConfig);
			if(headers != null && headers.size() > 0){
				Set<String> set = headers.keySet();
				for(String key : set){
					get.addHeader(key, headers.get(key));
				}
			}
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			if(entity == null)
				return null;
			return EntityUtils.toString(entity,charset);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(client != null)
				try {
					client.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
		}
	}

	/**
	 * 简单地址访问，使用GET方法请求，返回内容体
	 * @param url
	 */
	public static String doGet(String url,Map<String,String> headers){
		HttpClient client = null;
		try {
			client = new DefaultHttpClient();
			HttpGet get = new HttpGet(url);
			HttpParams params = client.getParams();
			HttpConnectionParams.setConnectionTimeout(params, 2000);
			HttpConnectionParams.setSoTimeout(params, 2000);
			if(headers != null && headers.size() > 0){
				Set<String> set = headers.keySet();
				for(String key : set){
					get.addHeader(key, headers.get(key));
				}
			}
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			if(entity == null)
				return null;
			return EntityUtils.toString(entity);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(client != null)
				client.getConnectionManager().shutdown();
		}
	}

	/**
	 * 简单地址访问，使用GET方法请求，返回内容体
	 * @param url
	 */
	public static Map<String,Object> doGet2(String url,Map<String,String> headers){
		DefaultHttpClient client = null;
		Map<String,Object> result = new HashMap<String,Object>();
		try {
			client = new DefaultHttpClient();
			HttpGet get = new HttpGet(url);
			if(headers != null && headers.size() > 0){
				Set<String> set = headers.keySet();
				for(String key : set){
					get.addHeader(key, headers.get(key));
				}
			}
			HttpResponse response = client.execute(get);
			int statusCode = response.getStatusLine().getStatusCode();
			result.put("statusCode", statusCode);
			result.put("headers", response.getAllHeaders());
			if(statusCode == 200){
				InputStream is = response.getEntity().getContent();
				int a = 0;
				long length = response.getEntity().getContentLength();

				length = length <= 0 ? 1024 : length;
				byte[] body = new byte[0];
				byte[] body_tmp = null;
				byte[] tmp = new byte[1024];
				while ((a = is.read(tmp)) != -1) {
					body_tmp = body;
					body = new byte[body_tmp.length + a];
					System.arraycopy(body_tmp, 0, body, 0, body_tmp.length);
					System.arraycopy(tmp, 0, body, body_tmp.length, a);
				}
				result.put("body", body);
			}
			return result;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(client != null)
				client.getConnectionManager().shutdown();
		}
	}

	/**
	 * 简单地址访问，使用GET方法请求，返回参数集合
	 * @param url
	 */
	public static Map<String,Object> downImage(String url,Map<String,String> headers,OutputStream out){
		HttpClient client = null;
		Map<String,Object> result = new HashMap<String,Object>();
		try {
			client = new DefaultHttpClient();
			HttpGet get = new HttpGet(url);
			if(headers != null){
				Set<String> set = headers.keySet();
				for(String key : set){
					get.addHeader(key, headers.get(key));
				}
			}
			HttpResponse response = client.execute(get);
			if(response.getStatusLine().getStatusCode() != 200){
				throw new RuntimeException("非200正常请求状态，statusCode="+response.getStatusLine().getStatusCode());
			}
			response.getEntity().writeTo(out);
			int statusCode = response.getStatusLine().getStatusCode();
			result.put("statusCode", statusCode);
			result.put("headers", response.getAllHeaders());
	        return result;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(client != null)
				client.getConnectionManager().shutdown();
		}
	}

	/**
	 * 直接從HTTP請求中返回JSON數據
	 */
	public static <T1> String doPostByJson(String url, T1 req) {
		String reqStr = JSON.toJSONString(req);
		String respStr = doPost(url, reqStr, CONTENT_TYPE_JSON_UTF8);
		return respStr;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T1,T2> T2 doPostByJson(String url,T1 req,Class<T2> clazz){
		String reqStr = JSON.toJSONString(req);
		String respStr = doPost(url,reqStr,CONTENT_TYPE_JSON_UTF8);
		try{
			return JSON.parseObject(respStr, clazz);
		}catch(Exception e){
			//暂时修复返回非数组解析出错问题
			respStr = respStr.replace("body", "bodyRep");
			T2 t2 = JSON.parseObject(respStr, clazz);
			List<Map<String,Object>> body = new LinkedList<Map<String,Object>>();
			try {
				Method m = t2.getClass().getMethod("getBodyRep");
				Map<String,Object> bodyRep = (Map<String,Object>)m.invoke(t2);
				body.add(bodyRep);
				m = t2.getClass().getMethod("setBody", List.class);
				m.invoke(t2, body);
				m = t2.getClass().getMethod("setBodyRep", Map.class);
				Map map = new HashMap();
				m.invoke(t2,map);
				return t2;
			} catch (Exception e1) {
				throw new RuntimeException(e1);
			}
		}
	}

	public static String doPost(String url,byte[] bytes, String contentType){
		HttpClient client = null;
		ByteArrayEntity byteEntity;
		try {
			client = new DefaultHttpClient();
			client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
			HttpPost post = new HttpPost(url);
			post.addHeader("Content-Type", contentType);
			byteEntity = new ByteArrayEntity(bytes);
			post.setEntity(byteEntity);
			HttpResponse response = client.execute(post);
			int respCode = response.getStatusLine().getStatusCode();
			HttpEntity entity = response.getEntity();
			if(entity == null){
				throw new RuntimeException("应答错误,应答实例为空！");
			}
			String respBody = EntityUtils.toString(entity,CONTENT_CHARSET_UTF8);
			if(respCode == 200){
				return respBody;
			}else{
				throw new RuntimeException("返回码"+response.getStatusLine().getStatusCode());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(client != null)
				client.getConnectionManager().shutdown();
		}
	}


	public static String doPost(String url,String postStr, int connectionTimeout, int soTimeout){
		HttpClient client = null;
		StringEntity strEntity;
		try {
			client = new DefaultHttpClient();
			client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
			HttpPost post = new HttpPost(url);
//			post.addHeader("Content-Type", contentType);
			postStr = postStr.trim();
			strEntity = new StringEntity(postStr,CONTENT_CHARSET_UTF8);
			post.setEntity(strEntity);
			HttpResponse response = client.execute(post);
			int respCode = response.getStatusLine().getStatusCode();
			HttpEntity entity = response.getEntity();
			if(entity == null){
				throw new RuntimeException("应答错误,应答实例为空！");
			}
			String respBody = EntityUtils.toString(entity,CONTENT_CHARSET_UTF8);
			if(respCode == 200){
				return respBody;
			}else{
				throw new RuntimeException("返回码"+response.getStatusLine().getStatusCode());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(client != null)
				client.getConnectionManager().shutdown();
		}
	}

	public static String doPost(String url,String postStr,String contentType){
		HttpClient client = null;
		StringEntity strEntity;
		try {
			client = new DefaultHttpClient();
			HttpPost post = new HttpPost(url);
			post.addHeader("Content-Type", contentType);
			strEntity = new StringEntity(postStr,CONTENT_CHARSET_UTF8);
			post.setEntity(strEntity);
			HttpResponse response = client.execute(post);
			int respCode = response.getStatusLine().getStatusCode();
			HttpEntity entity = response.getEntity();
			if(entity == null){
				throw new RuntimeException("应答错误,应答实例为空！");
			}
			String respBody = EntityUtils.toString(entity,CONTENT_CHARSET_UTF8);
			if(respCode == 200){
				return respBody;
			}else{
				throw new RuntimeException("返回码"+response.getStatusLine().getStatusCode());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(client != null)
				client.getConnectionManager().shutdown();
		}
	}


	public static Map<String,Object> doPost2(String url,String postStr,Map<String,String> headers){
		HttpClient client = null;
		StringEntity strEntity;
		Map<String,Object> result = new HashMap<String,Object>();
		try {
			client = new DefaultHttpClient();
			HttpPost post = new HttpPost(url);
			if(headers != null && headers.size() > 0){
				Set<String> set = headers.keySet();
				for(String key : set){
					post.addHeader(key, headers.get(key));
				}
			}
			if(StringUtils.isNotEmpty(postStr)){
				strEntity = new StringEntity(postStr,CONTENT_CHARSET_UTF8);
				post.setEntity(strEntity);
			}
			HttpResponse response = client.execute(post);
			int statusCode = response.getStatusLine().getStatusCode();
			result.put("statusCode", statusCode);
			result.put("headers", response.getAllHeaders());
			if(statusCode == 200){
				InputStream is = response.getEntity().getContent();
				int a = 0;
				long length = response.getEntity().getContentLength();
				length = length <= 0 ? 1024 : length;
				byte[] body = new byte[0];
				byte[] body_tmp = null;
				byte[] tmp = new byte[1024];
				while ((a = is.read(tmp)) != -1) {
					body_tmp = body;
					body = new byte[body_tmp.length + a];
					System.arraycopy(body_tmp, 0, body, 0, body_tmp.length);
					System.arraycopy(tmp, 0, body, body_tmp.length, a);
				}
				result.put("body", body);
			}
			return result;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(client != null)
				client.getConnectionManager().shutdown();
		}
	}

	/**
	 * 利用原生http get请求，非httpclient
	 */
	public static String doSimpleGet(String url,String contentType){
		HttpURLConnection conn = null;
		BufferedReader br = null;
		try {
			URL u = new URL(url);
			conn = (HttpURLConnection)u.openConnection();
			conn.setUseCaches(false);
			if(StringUtils.isNotEmpty(contentType))
				conn.setRequestProperty("Content-Type", contentType);
			conn.connect();
			br = new BufferedReader(new InputStreamReader(conn.getInputStream(),CONTENT_CHARSET_UTF8));
			StringBuilder sb = new StringBuilder();
			String str = null;
			while((str = br.readLine()) != null){
				sb.append(str);
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(br != null)
				try {
					br.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
		if(conn != null)
			conn.disconnect();
		return null;
	}

	/**
	 * 利用原生http post请求，非httpclient
	 */
	public static String doSimplePost(String url,String postStr,String contentType,String respCharset){
		HttpURLConnection conn = null;
		BufferedReader br = null;
		try {
			URL u = new URL(url);
			conn = (HttpURLConnection)u.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			if(StringUtils.isNotEmpty(contentType))
				conn.setRequestProperty("Content-Type", contentType);
			conn.setRequestMethod("POST");
			conn.connect();
			OutputStream outStrm = conn.getOutputStream();
			outStrm.write(postStr.getBytes());
			outStrm.flush();
			outStrm.close();
			br = new BufferedReader(new InputStreamReader(conn.getInputStream(),respCharset));
			StringBuilder sb = new StringBuilder();
			String str = null;
			while((str = br.readLine()) != null){
				sb.append(str).append("\n");
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(br != null)
				try {
					br.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
		if(conn != null)
			conn.disconnect();
		return null;
	}

	/**
	 *
	 * @param url
	 * @param postStr
	 * @param contentType
	 * @param outCharset 输出字符编码
	 * @param inCharset 读入字符编码
	 * @return
	 */
	public static String doPost(String url,String postStr,String contentType,String outCharset,String inCharset){
		HttpClient client = null;
		StringEntity strEntity;
		try {
			client = new DefaultHttpClient();
			HttpPost post = new HttpPost(url);
			if(StringUtils.isNotEmpty(contentType))
				post.addHeader("Content-Type", contentType);
			if(StringUtils.isEmpty(outCharset))
				outCharset = CONTENT_CHARSET_UTF8;
			strEntity = new StringEntity(postStr,outCharset);
			post.setEntity(strEntity);
			HttpResponse response = client.execute(post);
			int respCode = response.getStatusLine().getStatusCode();
			HttpEntity entity = response.getEntity();
			if(entity == null){
				throw new RuntimeException("应答错误,应答实例为空！");
			}
			if(StringUtils.isEmpty(inCharset))
				inCharset = CONTENT_CHARSET_UTF8;
			String respBody = EntityUtils.toString(entity,inCharset);
			if(respCode == 200){
				return respBody;
			}else{
				throw new RuntimeException("返回码"+response.getStatusLine().getStatusCode());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(client != null)
				client.getConnectionManager().shutdown();
		}
	}

	public static String doPost(String url,String postStr,Map<String,String> headers){
		HttpClient client = null;
		StringEntity strEntity;
		try {
			client = new DefaultHttpClient();
			HttpPost post = new HttpPost(url);
			if(headers != null && headers.size() > 0){
				Set<String> set = headers.keySet();
				for(String key : set){
					post.addHeader(key, headers.get(key));
				}
			}
			if(StringUtils.isNotEmpty(postStr)){
				strEntity = new StringEntity(postStr,CONTENT_CHARSET_UTF8);
				post.setEntity(strEntity);
			}
			HttpResponse response = client.execute(post);
			int respCode = response.getStatusLine().getStatusCode();
			HttpEntity entity = response.getEntity();
			if(entity == null){
				throw new RuntimeException("应答错误,应答实例为空！");
			}
			String respBody = EntityUtils.toString(entity,CONTENT_CHARSET_UTF8);
			if(respCode == 200){
				return respBody;
			}else{
				throw new RuntimeException("返回码"+response.getStatusLine().getStatusCode());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(client != null)
				client.getConnectionManager().shutdown();
		}
	}


	public static String postData(String urlStr, Map<String,Object> paramMap,String  accessToken ) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();

		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(urlStr);
			// 创建请求内容
			StringEntity entity = new StringEntity(JSONObject.toJSONString(paramMap), ContentType.APPLICATION_JSON);
			if(StringUtils.isNotBlank(accessToken)){
				httpPost.setHeader("Authorization",authPrix+accessToken);
			}
			httpPost.setEntity(entity);


			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				logger.error("postData is error:{}",e);
			}
		}
		return resultString;
	}


	/**
	 * 简单地址访问，使用POST方法请求，返回内容体
	 * @param url 访问地址
	 * @param paramsMap 请求参数列表
	 */
	public static String doPost(String url,Map<String,String> paramsMap){
		HttpClient client = null;
		UrlEncodedFormEntity uefEntity;
		try {
			client = new DefaultHttpClient();
			client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
			HttpPost post = new HttpPost(url);
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			String name = null;
			if(paramsMap != null){
				for(Iterator<String> it = paramsMap.keySet().iterator() ; it.hasNext() ;){
					name = it.next();
					formparams.add(new BasicNameValuePair(name,paramsMap.get(name)));
				}
			}
			uefEntity = new UrlEncodedFormEntity(formparams, CONTENT_CHARSET_UTF8);
			post.setEntity(uefEntity);
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			if(entity == null)
				return null;
			return EntityUtils.toString(entity);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(client != null)
				client.getConnectionManager().shutdown();
		}
	}

	/**
	 * 简单地址访问，使用POST方法请求，返回内容体
	 * @param url 访问地址
	 * @param paramsMap 请求参数列表
	 */
	public static String doPost(String url,Map<String,String> paramsMap,String charset){
		HttpClient client = null;
		UrlEncodedFormEntity uefEntity;
		try {
			client = new DefaultHttpClient();
			HttpPost post = new HttpPost(url);
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			String name = null;
			if(paramsMap != null){
				for(Iterator<String> it = paramsMap.keySet().iterator() ; it.hasNext() ;){
					name = it.next();
					formparams.add(new BasicNameValuePair(name,paramsMap.get(name)));
				}
			}
			uefEntity = new UrlEncodedFormEntity(formparams, "gb2312");
			post.setEntity(uefEntity);
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			if(entity == null)
				return null;
			return EntityUtils.toString(entity,charset);
		} catch (Exception e) {
			return null;
		}finally{
			if(client != null)
				client.getConnectionManager().shutdown();
		}
	}

	@SuppressWarnings("deprecation")
	public static HttpClient wrapClient(HttpClient base) {
	    try {
	        SSLContext ctx = SSLContext.getInstance("TLS");
	        X509TrustManager tm = new X509TrustManager() {
	            public void checkClientTrusted(X509Certificate[] xcs,
	                    String string) {
	            }
	            public void checkServerTrusted(X509Certificate[] xcs,
	                    String string) {
	            }
	            public X509Certificate[] getAcceptedIssuers() {
	                return null;
	            }
	        };
	        ctx.init(null, new TrustManager[]{tm}, null);
	        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
	        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
	        ClientConnectionManager ccm = base.getConnectionManager();
	        SchemeRegistry sr = ccm.getSchemeRegistry();
	        sr.register(new Scheme("https", ssf, 443));
	        return new DefaultHttpClient(ccm, base.getParams());
	    } catch (Exception ex) {
	        return null;
	    }
	}

	/**
	 * 简单地址访问，使用GET方法请求，返回内容体
	 * @param url
	 */
	public static String doGetByhttps(String url){
		HttpClient client = null;

		try {
			client = new DefaultHttpClient();
			client = wrapClient(client);
			HttpGet get = new HttpGet(url);
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			if(entity == null)
				return null;
			return EntityUtils.toString(entity);
		} catch (Exception e) {
			return null;
		}finally{
			if(client != null)
				client.getConnectionManager().shutdown();
		}
	}


	public static String doPost(String url, String param,String encoding, int socketTimeout, int connectTimeout) throws Throwable {
        String body = "";
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
	  try{
		//创建httpclient对象
	        client = HttpClients.createDefault();
	        //创建post方式请求对象
	        HttpPost httpPost = new HttpPost(url);
	        RequestConfig requestConfig = RequestConfig.custom()
	        		.setSocketTimeout(socketTimeout)
	        		.setConnectTimeout(connectTimeout)
	        		.build();

			httpPost.setConfig(requestConfig);
	        StringEntity strEntity = new StringEntity(param);
	        //设置参数到请求对象中
	        httpPost.setEntity(strEntity);
	        //设置header信息
	        //指定报文头【Content-type】、【User-Agent】
	        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
	        httpPost.setHeader("User-Agent", "Mozilla/3.0 (compatible; Indy Library)");

	        //执行请求操作，并拿到结果（同步阻塞）
	        response = client.execute(httpPost);
	        //获取结果实体
	        HttpEntity entity = response.getEntity();
	        if (entity != null) {
	            //按指定编码转换结果实体为String类型
	            body = EntityUtils.toString(entity, encoding);
	        }
	        EntityUtils.consume(entity);
	        return body;
	  }catch(Throwable e){
		  logger.error(e.getMessage(), e);
		  throw new Throwable(e);
	  }finally{
		  if (response != null)
			  response.close();

		  if (client != null)
			  client.close();
	  }
    }

	public static String postProtobuf(String url, byte[] content, String contentType, int sockettime, int contime) throws Throwable {
		String body = "";
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
	  try{
		//创建httpclient对象
	        client = HttpClients.createDefault();
	        //创建post方式请求对象
	        HttpPost httpPost = new HttpPost(url);
	        RequestConfig requestConfig = RequestConfig.custom()
	        		.setSocketTimeout(sockettime)
	        		.setConnectTimeout(contime)
	        		.build();

			httpPost.setConfig(requestConfig);
	        ByteArrayEntity bEntity = new ByteArrayEntity(content);
	        //设置参数到请求对象中
	        httpPost.setEntity(bEntity);
	        //设置header信息
	        httpPost.setHeader("Content-type", contentType);

	        //执行请求操作，并拿到结果（同步阻塞）
	        response = client.execute(httpPost);
	        //获取结果实体
	        HttpEntity entity = response.getEntity();
	        if (entity != null) {
	            //按指定编码转换结果实体为String类型
	            body = EntityUtils.toString(entity, CONTENT_CHARSET_UTF8);
	        }
	        EntityUtils.consume(entity);
	        return body;
	  }catch(Throwable e){
		  logger.error(e.getMessage(), e);
		  throw new Throwable(e);
	  }finally{
		  if (response != null)
			  response.close();

		  if (client != null)
			  client.close();
	  }
	}



}
